package com.srwl.mytx.im;

import android.content.Context;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.text.format.Time;
import android.util.Log;

import com.srwl.mytx.Helper;

import java.io.File;
import java.io.IOException;
import java.util.Date;


public class EaseVoiceRecorder {
    MediaRecorder recorder;

    static final String PREFIX = "voice";
    static final String EXTENSION = ".amr";

    private boolean isRecording = false;
    private long startTime;
    private String voiceFilePath = null;
    private String voiceFileName = null;
    private File audioFile;
    private Handler handler;

    public EaseVoiceRecorder(Handler handler) {
        this.handler = handler;
    }

    private static final String TAG = "EaseVoiceRecorder";

    /**
     * start recording to the audioFile
     */
    public String startRecording(Context appContext) {
        audioFile = null;
        try {
            // need to create recorder every time, otherwise, will got exception
            // from setOutputFile when try to reuse
            if (recorder != null) {
                recorder.release();
                recorder = null;
            }
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setAudioChannels(1); // MONO
            recorder.setAudioSamplingRate(8000); // 8000Hz
            recorder.setAudioEncodingBitRate(64); // seems if change this to
            // 128, still got same audioFile
            // size.
            // one easy way is to use temp audioFile
            // audioFile = File.createTempFile(PREFIX + userId, EXTENSION,
            // User.getVoicePath());
            // voiceFileName=Environment.getExternalStorageDirectory() + "/Android/data/" + appContext.getPackageName() + "/15334546663/";
            voiceFilePath = createAudioTempFile(Helper.getInstance().getFilePath() + File.separator);
            recorder.setOutputFile(voiceFilePath);
            recorder.prepare();
            isRecording = true;
            recorder.start();
        } catch (IOException e) {
//            EMLog.e("voice", "prepare() failed");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (isRecording) {
                        android.os.Message msg = new android.os.Message();
                        msg.what = recorder.getMaxAmplitude() * 13 / 0x7FFF;
                        handler.sendMessage(msg);
                        SystemClock.sleep(100);
                    }
                } catch (Exception e) {
                    // from the crash report website, found one NPE crash from
                    // one android 4.0.4 htc phone
                    // maybe handler is null for some reason
//                    EMLog.e("voice", e.toString());
                }
            }
        }).start();
        startTime = new Date().getTime();
//        EMLog.d("voice", "start voice recording to audioFile:" + audioFile.getAbsolutePath());
        return audioFile == null ? null : audioFile.getAbsolutePath();
    }

    public String createAudioTempFile(String fileRootPath) {
        File file1 = new File(fileRootPath);
        if (!file1.exists()) {
            boolean mkdirs = file1.mkdirs();

            if (!mkdirs) {
                Log.e(TAG, "createAudioTempFile: 语音文件存放目录创建失败 fileRootPath:" + fileRootPath);
            }
        }

        try {
            audioFile = File.createTempFile("audio_" + System.currentTimeMillis(), "", file1);
        } catch (IOException var4) {
            Log.w(TAG, "createAudioFile", var4);
        }
        return audioFile.getAbsolutePath();
    }

    /**
     * stop the recoding
     *
     * @return seconds of the voice recorded
     */

    public void discardRecording() {
        if (recorder != null) {
            try {
                recorder.stop();
                recorder.release();
                recorder = null;
                if (audioFile != null && audioFile.exists() && !audioFile.isDirectory()) {
                    audioFile.delete();
                }
            } catch (IllegalStateException e) {
            } catch (RuntimeException e) {
            }
            isRecording = false;
        }
    }

    public int stopRecoding() {
        if (recorder != null) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;

            if (audioFile == null || !audioFile.exists() || !audioFile.isFile()) {
//                return EMError.FILE_INVALID;
            }
            if (audioFile.length() == 0) {
                audioFile.delete();
//                return EMError.FILE_INVALID;
            }
            int seconds = (int) (new Date().getTime() - startTime) / 1000;
//            EMLog.d("voice", "voice recording finished. seconds:" + seconds + " audioFile length:" + audioFile.length());
            return seconds;
        }
        return 0;
    }

    protected void finalize() throws Throwable {
        super.finalize();
        if (recorder != null) {
            recorder.release();
        }
    }

    private String getVoiceFileName(String uid) {
        Time now = new Time();
        now.setToNow();
        return uid + now.toString().substring(0, 15) + EXTENSION;
    }

    public boolean isRecording() {
        return isRecording;
    }


    public String getVoiceFilePath() {
        return voiceFilePath;
    }

    public String getVoiceFileName() {
        return voiceFileName;
    }
}
